<?php

namespace App\Console\Commands\PolicyUpload;
use App\Http\Resources\BaseResource;
use App\Repositories\Contracts\PlatformInterface;
use App\Repositories\Contracts\PolicyInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class PolicyUploadCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'policy:upload';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(PolicyInterface $policyInterface)
    {
        //第一步上传携程

        $policyUploadService = new PolicyUploadService();
        $uploadTime = time();
        while (true) {

            try {

                $flightLineData = json_decode(Redis::rpop('policy:upload:list'),true);
                if ($flightLineData) {

                    //获取所有规则
                    $policy = $policyInterface->get(['status'=>1]);

                    //上传政策
                    $res = $policyUploadService->uploadPolicy($flightLineData['flights'],$policy);
                } else {
                    sleep(30);
                }

                //5秒钟上传一次
                if (time() - $uploadTime >= 5) {

                    $policyUploadService->otaUploadPolicy();

                    $uploadTime = time();
                }

            } catch (\Exception $exception) {

                logger('上传政策失败'.$exception->getMessage());
            }

        }
    }
}
